import { ref, h } from "vue";
import { uploadAndCheckDoc } from "@/api/sysupload";
import { message } from "@/utils/message";
import { type FormItemProps } from "../utils/types";
import pdfView from "../pdf.vue";
import { addDialog, closeDialog } from "@/components/ReDialog";

export function useRole() {
  const loading = ref(false);
  const fileList = ref([]);
  const beforeUpload = async file => {
    loading.value = true;
    const form = new FormData();
    form.append("file", file);
    uploadAndCheckDoc(form)
      .then(res => {
        loading.value = false;
        if (res.errno == 0) {
          message("校对成功", { type: "success" });
          console.log(JSON.stringify(res));
          openDialog(res.data);
          fileList.value = [];
          return false;
        } else {
          message("校对失败:" + res.message, { type: "error" });
          return false;
        }
      })
      .catch(error => {
        message("校对失败:" + JSON.stringify(error), { type: "error" });
        loading.value = false;
        return false;
      });
  };

  /** 超出最大上传数时触发 */
  const onExceed = () => {
    message("最多上传1个文件，请先删除在上传");
  };

  const beforeRemove = () => {
    return false;
  };

  //
  const formRef = ref();
  function openDialog(row?: FormItemProps) {
    addDialog({
      title: row?.name ?? "Pdf预览",
      props: {
        formInline: {
          id: row?.id ?? "",
          name: row?.name ?? "",
          word: row?.word ?? "",
          pdf: row?.pdf ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(pdfView, { ref: formRef }),
      footerButtons: [
        {
          label: "确定",
          type: "success",
          btnClick: ({ dialog: { options, index } }) => {
            closeDialog(options, index); // 关闭弹框
            location.reload();
          }
        }
      ]
    });
  }

  return {
    fileList,
    loading,
    beforeUpload,
    onExceed,
    beforeRemove
  };
}
